package com.gnerv.battle.boot.framework.core.tools;


import jakarta.servlet.http.HttpServletRequest;

/**
 * @Author Gnerv LiGen
 * @create 2023/6/14 15:18
 */
public class IpTools {

    private IpTools(){}

    private static final String UNKNOWN = "unknown";
    private static final String IP_SPLIT = ",";

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.contains(IP_SPLIT)) {
            return ip.split(",")[0];
        } else {
            return ip;
        }
    }

}
